__author__ = 'David Grace, Mark Creel, Matthew Naso, Jacob Bernhard'

from PyQt4 import QtCore, QtGui
import urllib2
import json

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):
    def setupUi(self, Form):
        tempForm = Ui_Form()

        Form.setObjectName(_fromUtf8("Form"))
        Form.resize(600, 50)
        self.horizontalLayoutWidget = QtGui.QWidget(Form)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(10, 0, 521, 51))
        self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
        self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setMargin(0)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.searchBar = QtGui.QLineEdit(self.horizontalLayoutWidget)
        self.searchBar.setEnabled(True)
        self.searchBar.setMaximumSize(QtCore.QSize(16777215, 30))
        self.searchBar.setObjectName(_fromUtf8("searchBar"))
        self.horizontalLayout.addWidget(self.searchBar)

        def handler():
            Form.resize(600,600)
            searchValue = str(self.searchBar.text())
            while self.toolBox.count() > 0:
                self.toolBox.removeItem(self.toolBox.count()-1)
            tempForm.updateUI(self.toolBox, RiakQuery().executeQuery("impression", searchValue))

        self.searchButton = QtGui.QPushButton(self.horizontalLayoutWidget)
        QtCore.QObject.connect(self.searchButton, QtCore.SIGNAL("clicked()"), handler)
        self.searchButton.setText(_fromUtf8("Search"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("searchButtonIcon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.searchButton.setIcon(icon)
        self.searchButton.setObjectName(_fromUtf8("searchButton"))
        self.horizontalLayout.addWidget(self.searchButton)
        self.line = QtGui.QFrame(Form)
        self.line.setGeometry(QtCore.QRect(0, 40, 541, 20))
        self.line.setFrameShape(QtGui.QFrame.HLine)
        self.line.setFrameShadow(QtGui.QFrame.Sunken)
        self.line.setObjectName(_fromUtf8("line"))
        self.toolBox = QtGui.QToolBox(Form)
        self.toolBox.setGeometry(QtCore.QRect(10, 70, 550, 500))
        self.toolBox.setObjectName(_fromUtf8("toolBox"))

        self.retranslateUi(Form)
        self.toolBox.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Medical Image Diagnosis Support System (MIDSS)", None))

    def showField(self, widget, currentCase, field):
        labelName = field+"Label"
        widget = QtGui.QLabel(widget)
        widget.setSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.MinimumExpanding)
        widget.setWordWrap(True)
        widget.setObjectName(_fromUtf8(labelName))
        widget.setText(_fromUtf8(field + ": " + currentCase.getData(field)))
        return widget

    def createCases(self, toolBox, QueryResults):
        currentCaseIndex = 0
        while currentCaseIndex < QueryResults.__len__():
            currentCase = QueryResults[currentCaseIndex]
            verticalLayoutWidget = QtGui.QWidget()
            verticalLayoutWidget.setGeometry(0, 0, 500, 500)
            verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget"))
            verticalLayout = QtGui.QVBoxLayout(verticalLayoutWidget)
            verticalLayout.setMargin(0)
            verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
            lblImage = QtGui.QLabel()
            verticalLayout.addWidget(lblImage)
            if currentCase.getImage() is not None:
                lblImage.setPixmap(QtGui.QPixmap(currentCase.getImage()))
            for field in currentCase.getAllData():
                currentWidget = Ui_Form().showField(verticalLayoutWidget, currentCase, field)
                verticalLayout.addWidget(currentWidget)
            verticalLayoutWidget.setLayout(verticalLayout)
            toolBox.addItem(verticalLayoutWidget, _fromUtf8(""))
            currentCaseText = "Case #" + str(currentCaseIndex + 1)
            toolBox.setItemText(toolBox.indexOf(verticalLayoutWidget), _fromUtf8(currentCaseText))
            currentCaseIndex += 1


    def updateUI(self, toolBox, QueryResults):
        self.createCases(toolBox, QueryResults)

class Case:
    def __init__(self):
        self.key = []
        self.value = []
        self.data = {}
        self.image = None

    def addData(self, key, value):
        self.data[key] = value

    def addImage(self, image):
        self.image = image

    def getAllData(self):
        return self.data

    def getData(self, key):
        return self.data[key]

    def getImage(self):
        return self.image

class RiakQuery:
    def __init__(self):
        pass

    def executeQuery(self, field, value):
        errorCounter = 0
        cases = []
        reportURL = "http://localhost:8098/search/query/report?q="+field+":"+value+"&wt=python"
        connection = urllib2.urlopen(reportURL)
        response = eval(connection.read())

        for document in response['response']['docs']:
            currentCase = Case()
            riakKey = document['_yz_rk']

            try:
                imageURL = "http://localhost:8098/types/jpg/buckets/jpg/keys/"+riakKey+".jpg"
                image = QtGui.QImage()
                imageData = urllib2.urlopen(imageURL).read()
                image.loadFromData(imageData)
                currentCase.addImage(image)
            except:
                print "No associated image"

            record = "http://localhost:8098/types/report/buckets/report/keys/"+riakKey
            jsonFile = urllib2.urlopen(record)
            try:
                jsonData = json.loads(jsonFile.read())
                for field in jsonData:
                    currentCase.addData(field, jsonData[field])

                cases.append(currentCase)
            except ValueError:
                errorCounter += 1
        return cases

if __name__ == "__main__":
    import sys
    tempQuery = RiakQuery()
    app = QtGui.QApplication(sys.argv)
    Form = QtGui.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())